package d512a.TAKO;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

import com.google.zxing.client.android.CaptureActivity;

import d512a.TAKO.helpers.DataBaseHelper;
import d512a.TAKO.helpers.DateHelper;

public class HomescreenActivity extends Activity {

    private String date;
    private DataBaseHelper foodDB;
    private String[][] newBarcodes = new String[][] {{"7340011404156", "276"},{"570131129166", "278"},{"5701318203934", "613"},
                    {"5701205005603", "964"}, {"5701318065495", "855"}, {"5701318106525", "337"}, {"5701232470894", "145"},
                    {"5701318123652", "166"}, {"7340011402619", "287"}, {"5709289005182", "314"}, {"5701318101155", "468"},
                    {"5012121000413", "788"}, {"5701410044343", "79"}, {"5701012549833", "162"}, {"5708567083546", "2"}, 
                    {"5701012098959", "975"}, {"5701012098942", "975"}, {"5701246106703", "996"}, {"5701246106710", "996"},
                    {"5701205006600", "997"}, {"8008698001073", "1005"}, {"5701246106680", "1004"}, {"5701246106598", "997"},
                    {"5701246006980", "1004"}, {"5701246106956", "1004"}, {"5711044004682", "997"}, {"5711044004606", "997"},
                    {"5701246103320", "997"}, {"5701246103344", "1004"}, {"5726866106070", "1004"}, {"5726866106063", "1004"},
                    {"5726866106438", "1004"}, {"5701246006379", "1004"}, {"5701129000036", "784"}, {"5060043220488", "784"},
                    {"7300400127479", "784"}, {"7300400127486", "784"}, {"5765228289792", "784"}, {"5765228290019", "784"},
                    {"5711044080273", "784"}, {"5711044080297", "784"}, {"5711044080310", "784"}, {"5701029014560", "468"},
                    {"5701029011835", "468"}, {"5701029160823", "792"}, {"5701869701026", "792"}, {"5705365011269", "43"}, 
                    {"4008569004381", "43"}, {"5701111000099", "793"}, {"5760466755276", "242"}, {"5760466931786", "244"},
                    {"5703985032015", "244"}, {"5704000432636", "337"}, {"5701295291061", "337"}, {"5701483457972", "261"},
                    {"5709749003246", "278"}, {"5701200102062", "278"}, {"5707196046038", "278"}, {"5704000001047", "278"},
                    {"5704000433480", "278"}, {"5704000001092", "278"}, {"5707196014686", "278"}, {"5707196070590", "278"},
                    {"292592600007", "278"}, {"5700426101415", "1016"}, {"5700426291154", "1016"}, {"5700426293912", "1006"},
                    {"5700426101217", "162"} };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homescreen);

        getWindow().setFormat(PixelFormat.RGBA_8888);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DITHER);

        if (!settingsSet()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder
                            .setMessage(
                                            "Velkommen til TaKO\n\nVil du oprette en profil i app'en?\n\nDet vil gøre TaKO bedre til at vejlede dig når du foretager indkøb.")
                            .setCancelable(false).setPositiveButton("Ja",
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    Intent intent = new Intent(
                                                                    HomescreenActivity.this,
                                                                    UserInfoActivity.class);
                                                    startActivity(intent);
                                                    dialog.dismiss();
                                                }
                                            }).setNegativeButton("Nej",
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    dialog.cancel();
                                                }
                                            });
            AlertDialog alert = builder.create();
            alert.show();
        }

        foodDB = new DataBaseHelper(this);

        try {
            foodDB.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        } finally {
            foodDB.close();
        }

        try {
            foodDB.openDataBase();
        } catch (SQLException sqle) {
            throw sqle;
        } finally {
            foodDB.close();
        }

        updateDB();

        date = DateHelper.getDate();

        ImageButton btnShoppingBasket = (ImageButton) findViewById(R.id.btnShoppingBasket);
        ImageButton btnHistory = (ImageButton) findViewById(R.id.btnHistory);
        ImageButton btnScanProduct = (ImageButton) findViewById(R.id.btnScanProduct);
        ImageButton btnAbout = (ImageButton) findViewById(R.id.btnAbout);
        ImageButton btnSettings = (ImageButton) findViewById(R.id.btnSettings);

        btnShoppingBasket.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent basketIntent = new Intent(HomescreenActivity.this, BasketActivity.class);
                basketIntent.putExtra("date", date);
                startActivity(basketIntent);
            }
        });

        btnScanProduct.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
                startActivity(intent);
            }
        });

        btnAbout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {  
                Intent intent = new Intent(HomescreenActivity.this, AboutActivity.class);
                startActivity(intent);
            }
        });

        btnHistory.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent historyIntent = new Intent(HomescreenActivity.this, HistoryActivity.class);
                startActivity(historyIntent);
            }
        });

        btnSettings.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent settingsIntent = new Intent(HomescreenActivity.this, UserInfoActivity.class);
                startActivity(settingsIntent);
            }
        });
    }

    private void updateDB() {
        new Thread(new Runnable() {
            public void run() {
                for(int i = 0; i < newBarcodes.length; i++){
                    if(!foodDB.barcodeExists(newBarcodes[i][0])){
                        foodDB.insertBarcodeInProducts(newBarcodes[i][0], newBarcodes[i][1]);
                    }
                }
            }
        }).start();
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            Thread t = new Thread() {
                public void run() {
                    Looper.prepare(); // For Preparing Message Pool for the
                    // child Thread
                    sendScannings(addScanningsToJSON());
                    sendRecommended(addRecommendedToJSON());
                    sendBasket(addBasketToJSON());

                    Looper.loop(); // Loop in the message queue
                }
            };
            t.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.homescreen_menu, menu);
        return true;
    }

    private void sendSettings(final JSONObject j) {
        sendData("Person", j);
    }

    private void sendScannings(final JSONObject j) {
        sendData("Scannings", j);

    }

    private void sendBasket(final JSONObject j) {
        sendData("Basket", j);
    }

    private void sendRecommended(final JSONObject j) {
        sendData("Recommended", j);
    }

    private void sendData(final String path, final JSONObject json) {
        if (json != null) {
            HttpPost request = new HttpPost("http://lino.herter.dk/Service.svc/" + path);

            try {
                StringEntity entity = new StringEntity(json.toString());
                Log.i("JSON: " + path, convertStreamToString(entity.getContent()));
                entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                request.setEntity(entity);

                // Send request to WCF service
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse response = httpClient.execute(request);

                if (response != null) {
                    String responce = convertStreamToString(response.getEntity().getContent());
                    responce = responce.trim();
                    Log.i("WebserviceResponce", responce);
                    if (responce.equals("\"1\"")) {
                        if (path.equals("Basket"))
                            foodDB.setSentBasket();
                        if (path.equals("Scannings"))
                            foodDB.setSentScannings();
                        if (path.equals("Recommended"))
                            foodDB.setSentRecommended();
                    }
                } else {
                    Log.i("WebserviceError", "Responce == null");
                }
            } catch (Exception e) {
                Log.i("WebserviceError", e.toString());
            }
        }
    }

    private JSONObject addPersonalDataToJSON() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        JSONObject json = new JSONObject();

        try {
            json.put("sex", getSharedPreferences("prefs", 0).getString("sex", "-1"));
            json.put("height", getSharedPreferences("prefs", 0).getString("height", "-1"));
            json.put("weight", getSharedPreferences("prefs", 0).getString("weight", "-1"));
            json.put("year", getSharedPreferences("prefs", 0).getString("year", "-1"));
            json.put("month", getSharedPreferences("prefs", 0).getString("month", "-1"));
            json.put("day", getSharedPreferences("prefs", 0).getString("day", "-1"));
            json.put("imei", telephonyManager.getDeviceId());
            json.put("email", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return json;
    }

    private JSONObject addScanningsToJSON() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        JSONObject json = new JSONObject();
        ArrayList<String> barcodeArray = new ArrayList<String>();
        ArrayList<Integer> idArray = new ArrayList<Integer>();
        ArrayList<String> dateArray = new ArrayList<String>();

        Cursor cursor = foodDB.getScannings();
        if (cursor.getCount() == 0) {
            return null;
        } else {
            cursor.moveToFirst();
            for (int i = 0; i < cursor.getCount(); i++) {
                idArray.add(cursor.getInt(0));
                barcodeArray.add(cursor.getString(1));
                dateArray.add(cursor.getString(2));

                cursor.moveToNext();
            }
            try {
                json.put("imei", telephonyManager.getDeviceId());
                json.put("scan_id", idArray);
                json.put("barcodes", barcodeArray);
                json.put("dates", dateArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            cursor.close();
            return json;
        }
    }

    private JSONObject addRecommendedToJSON() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        JSONObject json = new JSONObject();
        ArrayList<Integer> ProductArray = new ArrayList<Integer>();
        ArrayList<Integer> scanIDArray = new ArrayList<Integer>();
        ArrayList<Integer> recIDArray = new ArrayList<Integer>();
        ArrayList<Integer> IDArray = new ArrayList<Integer>();
        ArrayList<Integer> suggTypeArray = new ArrayList<Integer>();
        ArrayList<String> dates = new ArrayList<String>();

        Cursor cursor = foodDB.getRecommended();
        if (cursor.getCount() == 0) {
            return null;
        } else {
            cursor.moveToFirst();

            for (int i = 0; i < cursor.getCount(); i++) {
                IDArray.add(cursor.getInt(0));
                ProductArray.add(cursor.getInt(1));
                recIDArray.add(cursor.getInt(3));
                scanIDArray.add(cursor.getInt(4));
                suggTypeArray.add(cursor.getInt(5));
                dates.add(cursor.getString(6));

                cursor.moveToNext();
            }
            try {
                json.put("imei", telephonyManager.getDeviceId());
                json.put("scan_id", scanIDArray);
                json.put("rec_id", recIDArray);
                json.put("id", IDArray);
                json.put("suggestion_id", suggTypeArray);
                json.put("productnames", ProductArray);
                json.put("date", dates);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            cursor.close();
            return json;
        }
    }

    private JSONObject addBasketToJSON() {
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        JSONObject json = new JSONObject();
        ArrayList<Integer> ProductArray = new ArrayList<Integer>();
        ArrayList<Integer> QuantityArray = new ArrayList<Integer>();
        ArrayList<String> DateArray = new ArrayList<String>();
        ArrayList<Integer> SuggestedArray = new ArrayList<Integer>();
        ArrayList<Integer> ScanIDArray = new ArrayList<Integer>();

        Cursor cursor = foodDB.getBasket();

        if (cursor.getCount() == 0) {
            return null;
        } else {
            cursor.moveToFirst();

            for (int i = 0; i < cursor.getCount(); i++) {
                ProductArray.add(cursor.getInt(1));
                QuantityArray.add(cursor.getInt(2));
                DateArray.add(cursor.getString(3));
                SuggestedArray.add(cursor.getInt(4));
                ScanIDArray.add(cursor.getInt(6));

                cursor.moveToNext();
            }
            try {
                json.put("imei", telephonyManager.getDeviceId());
                json.put("productnames", ProductArray);
                json.put("quantity", QuantityArray);
                json.put("rec_id", SuggestedArray);
                json.put("scan_id", ScanIDArray);
                json.put("dates", DateArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            cursor.close();
            return json;
        }
    }

    private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    private boolean settingsSet() {
        if (getSharedPreferences("prefs", 0).getString("sex", "-1") != "-1") {
            SharedPreferences settings = getSharedPreferences("prefs", 0);
            SharedPreferences.Editor editor = settings.edit();

            if (!getSharedPreferences("prefs", 0).getBoolean("setSettings", false)) {
                sendSettings(addPersonalDataToJSON());
                editor.putBoolean("setSettings", true);
                editor.commit();
            }
            return true;
        } else {
            return false;
        }
    }
}
